#include "interface.h"

using namespace std;

Database::Database(std::string dbfile)
{
    int rc;
    char* errmsg;

    if (sqlite3_open(dbfile.c_str(), &db))
    {
        cout << sqlite3_errmsg(db) << endl;
        sqlite3_close(db);
        return;
    }

    string cmd = "create table if not exists punch (id text, time integer)";
    rc = sqlite3_exec(db, cmd.c_str(), nullptr, nullptr, &errmsg);
    if (rc != SQLITE_OK)
    {
        cout << errmsg << endl;
        sqlite3_free(errmsg);
    }

    cmd = "create table if not exists employee (id text primary key, name text);"
          "insert into employee values (\"liuyu\", \"刘煜\")";
    rc = sqlite3_exec(db, cmd.c_str(), nullptr, nullptr, &errmsg);
    if (rc != SQLITE_OK)
    {
        cout << errmsg << endl;
        sqlite3_free(errmsg);
    }
}

int Database::punch(std::string id, time_t time)
{
    int rc;
    char* errmsg;

    if (!db)
    {
        cout << "database not open" << endl;
        return 1;
    }
    string cmd = "insert into punch values (\"" + id + "\", " + to_string(time) + ")";
    rc = sqlite3_exec(db, cmd.c_str(), nullptr, nullptr, &errmsg);
    if (rc != SQLITE_OK)
    {
        cout << errmsg << endl;
        sqlite3_free(errmsg);
        return 2;
    }

    return 0;
}

static int getname_cb(void* data, int argc, char** argv, char** col)
{
    string* value = reinterpret_cast<string*>(data);
    *value = argv[0];
    return 0;
}

int Database::getname(string id, string& name)
{
    int rc;
    char* errmsg;

    string cmd = "select name from employee where id = \"" + id + "\"";
    rc = sqlite3_exec(db, cmd.c_str(), getname_cb, &name, &errmsg);
    if (rc != SQLITE_OK)
    {
        cout << errmsg << endl;
        sqlite3_free(errmsg);
        return 2;
    }
    return 0;
}

Database::~Database()
{
    if (!db) return;
    sqlite3_close(db);
    db = nullptr;
}
